﻿// Decompiled with JetBrains decompiler
// Type: Microsoft.InfoCards.SystemIdentity
// Assembly: infocard, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// MVID: 8E14765A-6610-409A-BA36-099A0642905D
// Assembly location: E:\git\ALLIDA\windll\infocard.exe

using Microsoft.InfoCards.Diagnostics;
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security.Principal;

namespace Microsoft.InfoCards
{
  internal sealed class SystemIdentity : IDisposable
  {
    public static readonly IdentityReference LsaIdentityReference = (IdentityReference) new SecurityIdentifier("SY");
    private bool m_isDisposed;
    private WindowsIdentity m_identity;
    private object m_sync;

    public SystemIdentity(bool throwIfAlreadySystem)
    {
      this.m_sync = new object();
      WindowsIdentity current = WindowsIdentity.GetCurrent();
      if (current.IsSystem && throwIfAlreadySystem)
        throw InfoCardTrace.ThrowHelperError((Exception) new InvalidOperationException(SR.GetString("UserIdentityEqualSystemNotSupported")));
      if (!current.IsSystem)
      {
        this.m_identity = current;
        if (NativeMethods.RevertToSelf())
          return;
        InfoCardTrace.Assert(false, "Identity management failure");
      }
      else
        InfoCardTrace.Assert(null == this.m_identity, "m_identity should be null when we are system and throwIfAlreadySystem == false");
    }

    void IDisposable.Dispose()
    {
      if (this.m_isDisposed)
        return;
      lock (this.m_sync)
      {
        if (this.m_isDisposed)
          return;
        this.m_isDisposed = true;
        if (this.m_identity == null)
          return;
        if (!NativeMethods.ImpersonateLoggedOnUser(this.m_identity.Token))
          InfoCardTrace.FailFast(string.Format((IFormatProvider) CultureInfo.InvariantCulture, SR.GetString("StoreImpersonateLoggedOnUserFailed"), (object) Marshal.GetHRForLastWin32Error()));
        this.m_identity.Dispose();
      }
    }
  }
}
